package com.ljxt.dt.web.listener;

import com.alibaba.druid.pool.DruidDataSource;
import com.ljxt.dt.util.DaoUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 唐春劲
 * @version 1.0.0
 * @date 2020-05-05 17:15
 * @copyright 老九学堂
 */

public class DataSourceListener implements ServletContextListener  {
    //记录配置文件路径
    private  String configLocation;
    private static  final String CLASSPATH_PATTERN = "classpath:";
    private static final  String CLASSPATH = "/WEB-INF/classes/";
    private static  final  String WEBCLASS = "/WEB-INF/";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //获取上下文环境
        ServletContext application = sce.getServletContext();
        application.setAttribute("ctx",application.getContextPath()+"/");
        //获取全局配置里的名称
        configLocation = application.getInitParameter("datasource");
        //根据路径获取资源
        String path =  parseConfigLocation(configLocation);
        //创建properties
        Properties properties = new Properties();
        try {

            properties.load(application.getResourceAsStream(path));


        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取连接池对象
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
        druidDataSource.setUrl(properties.getProperty("jdbc.url"));
        druidDataSource.setUsername(properties.getProperty("jdbc.username"));
        druidDataSource.setPassword(properties.getProperty("jdbc.password"));
        druidDataSource.setMaxActive(10);
        //将对象设置进去
        DaoUtil.setDataSource(druidDataSource);

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    private String parseConfigLocation(String path){
        if(path.startsWith(CLASSPATH_PATTERN)){
            path = CLASSPATH + path.substring(CLASSPATH_PATTERN.length());
        }else{
            path = WEBCLASS+path;
        }

        return path;
    }
}
